package com.chengliang.bbs.entry;

import com.chengliang.bbs.type.UserIdentityType;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Id;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 授权（登录信息记录）信息表
 * 一个用户拥有多个登录方式（登录信息）
 * @author chengliang
 */
@Data
@Accessors(chain = true)
public class UserAuths implements Serializable,UserDetails {
    /**
    * 主键
    */
    @Id
    private Integer userAuthsId;

    /**
    * 用户ID
    */
    private Integer userId;

    /**
     * 用户信息
     */
    private User user;

    /**
     * 权限
     */
    private String userAuthorities;

    /**
    * 授权类型 QQ、weixin、weibo
    */
    private UserIdentityType userIdentityType;

    /**
    * 账号 邮箱、手机号、openId
    */
    private String userIdentifier;

    /**
    * 密码 第三方登录则为token
    */
    private String userCredential;

    /**
    * 1未验证  0已验证
    */
    private Integer userIfverified;

    /**
     * 用户权限
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ROLE_"+(this.userAuthorities==null?"user":this.userAuthorities)));
        return auths;
    }

    /**
     * 密码
     * @return
     */
    @Override
    public String getPassword() {
        return this.userCredential;
    }

    /**
     * 登录名
     * @return
     */
    @Override
    public String getUsername() {
        return userIdentifier;
    }

    /**
     * 账号是否到期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }


    /**
     * 账号是否锁定
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 证书是否过期
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账号是否启用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return user != null && user.getUserIsEnable()==0;
    }
}